import os, traceback
from sys import stderr

class Properties(object):

    def __init__(self, fileName):
        self.fileName = fileName
        self.properties = {}

    def __getDict(self, strName, dictName, value):

        if (strName.find(',') > 0):
            k = strName.split(',')[0]
            dictName[k] = value
            return self.__getDict(strName[len(k) + 1:], dictName, value)
        else:
            dictName[strName] = value
            return

    def readProperties(self):
        try:
            dictName = None
            linecount = 0
            if os.path.exists(self.fileName) == False:
                raise PropException('NOTFOUND', linecount)
            pro_file = open(self.fileName, 'Ur', encoding='utf-8')
            for line in pro_file.readlines():
                linecount +=1
                line = line.strip().replace('\n', '')
                if len(line)==0 or line.find("#") == 0:
                    continue
                elif line.find('<') == 0:
                    if line[-1] != '>':
                        raise PropException('UNCOMP', linecount)
                    dictName = line[1:-1]
                    self.properties[dictName] = {}
                elif line[-1] == '>':
                    raise PropException('UNCOMP', linecount)
                else:
                    if line.find('=') > 0:
                        strs = line.split('=')
                        value = line[len(strs[0]) + 1:].strip()
                        if value in self.properties.keys():
                            value = self.properties[value]
                        self.__getDict(strs[0].strip(), self.properties[dictName], value)
                    else:
                        raise PropException('VALID',linecount)
        except PropException as e:
            traceback.print_exc()
            print(e.message, file = stderr)
            exit(1)
        return self.properties

    def __chkKeyGet(self, dic, key):
        if not isinstance(dic, dict) or key not in dic.keys():
            raise PropException('PATH', 0)
        else:
            return dic[key]

    def getProperties(self, path):
        parent = self.properties
        try:
            while path.find('.') > 0:
                pName = path.split('.')[0]
                path = path[len(pName) + 1:]
                parent = self.__chkKeyGet(parent, pName)
            return self.__chkKeyGet(parent, path)
        except PropException as e:
            traceback.print_exc()
            print(e.message, file=stderr)
            exit(1)


class PropException(Exception):
    def __init__(self,type, line):
        Exception.__init__(self)
        if type == 'UNCOMP':
            self.message="Cannot find '<' or '>' in property file"
        if type == 'VALID':
            self.message='Failed to read properties'
        if type == 'NOTFOUND':
            self.message='File is not exist'
        if type == 'PATH':
            self.message='Access path is wrong'
        self.message += ' [lines:%d]' % line
